﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Diagnostics.Contracts;
using Clipping.Infrastructure.Models;

namespace Clipping.Utils.SearchEngines
{
    public class BaiduWeb : ISearchEngine
    {

        private Encoding _urlEncoding = Encoding.GetEncoding("gb2312");
        private Encoding _contentEncoding = Encoding.UTF8;
        public void Parse(Uri url, string html, out List<News> news, out string nextPageUrl)
        {
            parse(html, out news, out nextPageUrl);
            if (!string.IsNullOrEmpty(nextPageUrl))
                nextPageUrl = constructAbsoluteUrl(url, nextPageUrl).OriginalString;
            if (news != null)
            {
                foreach (var n in news)
                {
                    if (!string.IsNullOrEmpty(n.SameNewsUrl))
                        n.SameNewsUrl = constructAbsoluteUrl(url, n.SameNewsUrl).OriginalString;
                }
            }
        }

        public Uri ConstructUrl(SearchObject searchObj)
        {
            return constructUrl(searchObj);
        }
        public void Search(Infrastructure.Models.SearchObject searchObj, IHtmlDownload downloader, out List<Infrastructure.Models.News> news, out string nextPageUrl)
        {
            var url = constructUrl(searchObj);
            string html = downloader.GetHtml(url);
            parse(html, out news, out nextPageUrl);
            if (!string.IsNullOrEmpty(nextPageUrl))
                nextPageUrl = constructAbsoluteUrl(url, nextPageUrl).OriginalString;
            if (news != null)
            {
                foreach (var n in news)
                {
                    if (!string.IsNullOrEmpty(n.SameNewsUrl))
                        n.SameNewsUrl = constructAbsoluteUrl(url, n.SameNewsUrl).OriginalString;
                }
            }
        }

        #region 私有方法
        private Uri constructUrl(Infrastructure.Models.SearchObject searchObj)
        {
            return new Uri(string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(searchObj.Keyword, this._urlEncoding)));
        }
        public Uri constructAbsoluteUrl(Uri baseUri, string url)
        {
            return UriHelper.ConstructAbsoluteUrl(baseUri, url);
        }

        private void parse(string html, out List<News> news, out string nextPageUrl)
        {
            news = new List<News>();
            nextPageUrl = null;
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var liNav = doc.CreateNavigator();
            var lis = liNav.Select("//div[@id='content_left']/div[contains(@class,'result') and not(contains(@class,'xpath-log') )]");

            while (lis.MoveNext())
            {
                News n = new News();

                var li = lis.Current;

                var link = li.SelectSingleNode("descendant::h3/a");
                if (link != null)
                {
                    n.Title = link.Value;
                    n.Title = System.Web.HttpUtility.HtmlDecode(n.Title);
                    n.Url = link.GetAttribute("href", "");
                }

                var summary = li.SelectSingleNode("descendant::div[@class='c-abstract']");
                if (summary != null)
                    n.Summary = summary.Value;
                news.Add(n);
            }
            var nextPage = liNav.SelectSingleNode("//p[@id='page']/a[last()]");
            if (nextPage != null && nextPage.Value != null && nextPage.Value.Contains("下一页"))
            {
                nextPageUrl = nextPage.GetAttribute("href", "");
            }

        }
       
        #endregion

        #region 属性
        public string Name
        {
            get { return "百度网页搜索"; }
        }
        public Encoding ContentEncoding
        {
            get { return _contentEncoding; }
        }
        #endregion




     
    }
}
